package csci5828.servlet;

import java.io.IOException;
import java.io.PrintStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import csci5828.tasks.RequestId;
import csci5828.tasks.TaskManager;
import csci5828.tasks.TaskResults;

public class WaitTaskResultsServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		PrintStream out = new PrintStream(resp.getOutputStream());
		
		resp.setContentType("text/plain");
		resp.setHeader("Cache-Control", "no-cache");
		
		// Get the requestId parameter
		String requestIdStr = req.getParameter("requestId");
		if (requestIdStr == null) {
			out.println("Invalid request id "+requestIdStr);
			resp.setStatus(403);
			out.close();
			return;
		}
		
		try {
    		RequestId requestId = new RequestId(Long.valueOf(requestIdStr));
    		TaskManager<String> taskManager = TaskManagerUtil.getInstance().taskManager;
    		TaskResults<String> results = taskManager.getResults(requestId);
    		
    		// Check if the user gave us a requestId that doesn't exist.
    		if (results == null) {
    			out.println("Invalid request id "+requestIdStr);
    			resp.setStatus(403);
    			out.close();
    			return;
    		}
    		
    		// Print any results that are already available
    		for (String result: results.getAvailableResults())
    			out.println(result);
    		out.flush();
    		
    		// If there are still pending results, wait for the next result 
    		if (results.isPending()) {
    			if (results.next()) {
    				if (results.get() != null)
            			out.println(results.get());
    				else
    					out.println("@END@");
    			}
    			out.flush();
    		} else {
    			// No more results, send EL FIN
    			out.println("@END@");
    		}
    		
		} catch (NumberFormatException e) {
			out.println("Invalid request id "+requestIdStr);
			resp.setStatus(403);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		out.close();
		
	}
}
